<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="com.google.appengine.api.datastore.KeyFactory" %>
<%@ page import="javax.jdo.PersistenceManager" %>
<%@ page import="connectfour.PMF" %>
<%@ page import="connectfour.Game" %>
<%@ page import="connectfour.Player" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.Date" %>
<%@ page import="javax.jdo.Query" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Playing QUAD ATTACK!</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src='/_ah/channel/jsapi'></script>
<script type="text/javascript"
 src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>

</head>
<body>
	<%
		PersistenceManager pm = PMF.get().getPersistenceManager();
	
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		Query query1 = pm.newQuery(Player.class);
		query1.declareImports("import com.google.appengine.api.users.User");
		query1.setFilter("player == playerParam");
		query1.setUnique(true);
		query1.declareParameters("User playerParam");
		
		Player player;
		
		try {
			Player result = (Player) query1.execute(user);
			if (result != null) {
				player = result;
			} else {
				player = new Player(user);
				pm.makePersistent(player);
			}
		} finally {
			query1.closeAll();
		}
		
		Game game;
		
		try {
			game = pm.getObjectById(Game.class, KeyFactory.createKey("Game", 
					Long.parseLong(request.getParameter("gameID"))));
		} catch(javax.jdo.JDOObjectNotFoundException e){
			game = new Game(player.getKey(), new Date());
		}
		
		int status;
		
		if(player.getPlayer().equals(game.getUserHost()))	status = 1;
		else if(player.getPlayer().equals(game.getUserOpponent())) status = 2;
		else status = -1;
	%>


	<%if(!game.isOver()){ %>
	<center>
		<a href="menu.jsp">SUSPEND GAME</a>
	</center>
	<%} %>

	<% if(game.isOver()) { %>
	
	<div id ="winner"><center>
		<% if(game.getWinner() == 0){ %>
			<h1>Opponent has left the game</h1>

		<% } else { %>
			<h1>Player <%= game.getWinner() %> has won!</h1>
		<% } %>
		<h2>Click "Quit Game" to return to the lobby</h2>
	</center></div>
	<% }else{ %>
	<div id ="winner" style="display:none;"></div>
	<% } %>
	
	<center>
		<form action="/quit?gID=<%=game.getKey().getId()%>" method="post">
		<input type="submit"value="Quit Game">
		</form><br /><br />
	</center>
	
	
	<table id = "board">
	
	<% if(game.getTurn() == 0) { %>
		<tr><th id="waiting" colspan="8">Waiting for an opponent</th></tr>
	<% }else if(game.getTurn() % 2 != 0 && !game.isOver()){ %>
		<tr><th colspan="8">Player <span id="currentPlayer">1</span>'s turn</th></tr>
	<%}else if(!game.isOver()){%>
		<tr><th colspan="8">Player <span id="currentPlayer">2</span>'s turn</th></tr>
	<% } %>
	<tr>
	<% for(int y = 0; y < 8; y++) { %>
		<td class="cell_header">
		<% if((game.getTurn() % 2 == status % 2)
			&& game.getNumPieces().get(y) < 8
			&& !game.isOver())  { %>
			<form action="/move?gameID=<%=game.getKey().getId()%>&col=<%=y%>&pID=<%=status%>" method="post" class="forms">
			<input class="submits" type="submit" value="SEL">
			</form>
		<% }else{ %>
			<form style="display: none;" action="/move?gameID=<%=game.getKey().getId()%>&col=<%=y%>&pID=<%=status%>" method="post" class="forms">
			<input class="submits" type="submit" value="SEL" disabled="disabled"">
			</form>
		<% } %>
		</td>
	<% } %>
	</tr>
	<% for(int y = 7; y >= 0; y--) { %>
		<tr>
			<% for(int x = 0; x < 8; x++) { %>
				<% String c; %>
				<% 
				   if(game.getValue(x,y) == 1) c = "black";
				   else if(game.getValue(x,y) == 2) c = "red";
				   else c = "empty"; 
				%>
				
				<td id="cell<%= x %><%= y %>" class="<%= c %>_cell">
				</td>


			<% } %>
		</tr>
	<% } %>
	</table>
	
<script language="javascript">
	turn = <%= game.getTurn() %>;
	function updateTime()
	{
		if (window.XMLHttpRequest)
		{// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp=new XMLHttpRequest();
		}
		else
		{// code for IE6, IE5
			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
		
		xmlhttp.onreadystatechange=function()
		{
			if (xmlhttp.readyState==4 && xmlhttp.status==200)
			{
				var response = xmlhttp.responseText.split(" ")
				
				if(response[0] == "change" || response[0] == "over") {
					x = response[1]
					y = response[2]
					$("#cell"+x+""+y).removeClass("empty_cell")
					$("#cell"+x+""+y).addClass(response[3]+"_cell")
					
					if(turn == 0) $("#waiting").text("An opponent has joined your game")
					
					turn = response[4];
					
					if(response[0] == "change"){
						$(".forms").show()
						$(".submits").removeAttr("disabled")
						p = $("#currentPlayer").text()
						if(p == "1") $("#currentPlayer").text("2")
						else $("#currentPlayer").text("1")
					}
					else{
						if(response[5] != 0) {
							$("#winner").html("<center><h1>Player "+ response[5] +" has won!</h1></center>")
							$("#winner").show();
						}
					}
				}
			}
		}
		xmlhttp.open("GET", "move?gameID=<%= game.getKey().getId() %>&turn="+turn, true);
		xmlhttp.send(null);
	}
	
	setInterval(updateTime, 3000);
	
	$(".submits").click(function(){
		turn++
		p = $("#currentPlayer").text()
		if(p == "1") $("#currentPlayer").text("2")
		else $("#currentPlayer").text("1")
	})
</script>
</body>
</html>